package foundation.tree.binaryTree.二叉树的序列化与反序列化;


/**
 * @author hang an
 * @since 2025/7/12
 */
public class 先序 {

    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        enF(root, sb);
        return sb.toString();
    }

    public void enF(TreeNode node, StringBuilder sb) {
        if (node == null) {
            sb.append("#,");
            return;
        }
        sb.append(node.val).append(",");
        enF(node.left, sb);
        enF(node.right, sb);
    }

    public TreeNode deserialize(String data) {
        if (data == null || data.isEmpty()) return null;
        String[] allTreeNode = data.split(",");
        return enF(allTreeNode);
    }
    private int index = 0;
    public TreeNode enF(String[] allTreeNode) {
        String cur = allTreeNode[index++];
        if (cur.equals("#")) return null;
        TreeNode node = new TreeNode(Integer.parseInt(cur));
        node.left = enF(allTreeNode);
        node.right = enF(allTreeNode);
        return node;
    }
}
